//
//  OneFeedViewController.m
//  xxShare
//
//  Created by 柳麟喆 on 2018/3/29.
//  Copyright © 2018年 lzLiu. All rights reserved.
//

#import "OneFeedViewController.h"
#import "FeedCell.h"
#import "FeedModel.h"
#import "LLZStatusBarAlertView.h"
#import "VisitViewController.h"
#import "XLPhotoBrowser.h"
#import "CommentCell.h"
#import "CommentView.h"
#import "UIButton+LLZ.h"

@interface OneFeedViewController ()<UITableViewDelegate, UITableViewDataSource, FeedCellDelegate, XLPhotoBrowserDelegate>


@property(nonatomic, strong)UITableView *tableview;
@property(nonatomic, strong)CommentView *commentView;
@property(nonatomic, strong)NSMutableArray *testData;//优质内容例子
@property(nonatomic, strong)NSMutableArray *commentData;//评论内容例子

@end

@implementation OneFeedViewController

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"胖虎发表";
    
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.llz_width, self.view.llz_height - 40) style:UITableViewStyleGrouped];
    _tableview.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    _tableview.dataSource = self;
    _tableview.delegate = self;
    _tableview.estimatedRowHeight = 200;
    _tableview.estimatedSectionFooterHeight = 0;
    _tableview.backgroundColor = [UIColor whiteColor];
    _tableview.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [self.view addSubview:_tableview];
    
    _commentView = [[CommentView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 46, SCREEN_WIDTH, 46)];
    // 监听文本框文字高度改变
    __weak typeof(_commentView) weakView = _commentView;
    __weak typeof(self)weakSelf = self;
    [_commentView.inputView textValueDidChanged:^(NSString *text, CGFloat textHeight) {
        __strong typeof(weakView) strongView = weakView;
        //更改inputView的高度
        CGRect frame = strongView.inputView.frame;
        frame.size.height = textHeight;
        strongView.inputView.frame = frame;
        //更改commentView的高度与偏移量
        CGRect commentFrame = strongView.frame;
        commentFrame.origin.y = commentFrame.origin.y - textHeight + commentFrame.size.height - 10;
        commentFrame.size.height = textHeight + 10;
        strongView.frame = commentFrame;
        [weakSelf.view layoutIfNeeded];
    }];
    _commentView.inputView.maxNumberOfLines = 4;
    [self.view addSubview:_commentView];
    
    //评论点击事件
    [_commentView.publishBtn addHander:^{
        [weakSelf commentAndReplyWithType:0];//评论
    }];
    
    // 监听键盘弹出
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    //添加测试数据
    _testData = [[NSMutableArray alloc]init];
    _testData = [self addTestData];;
    _commentData = [[NSMutableArray alloc]init];
    _commentData = [self addCommentData];
}

#pragma mark - *******tableview DataSource*******
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 1) {//评论
        return _commentData.count;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //有评论的情况
    if (indexPath.section == 1) {
        static NSString *kCommentID = @"commentID";
        CommentCell *commentCell = [tableView dequeueReusableCellWithIdentifier:kCommentID];
        if (!commentCell) {
            commentCell = [[[NSBundle mainBundle]loadNibNamed:@"CommentCell" owner:self options:nil]firstObject];
            commentCell.model = _commentData[indexPath.row];
        }
        return commentCell;
    }

    FeedCell *feedCell = [tableView cellForRowAtIndexPath:indexPath];
    if (!feedCell) {
        feedCell = [[[NSBundle mainBundle]loadNibNamed:@"FeedCell" owner:self options:nil]firstObject];
    }
    [self configureCell:feedCell atIndexPath:indexPath];
    return feedCell;//返回个人信息cell
}

- (void)configureCell:(FeedCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.delegate = self;
    //数据刷新
    FeedModel *model = _testData[indexPath.section];
    cell.model = model;
    cell.commentNum.textColor = [UIColor redColor];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"";
    }
    return @"以下为评论";
}

#pragma mark - *******tableview Delegate*******
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView cellForRowAtIndexPath:indexPath].selected = NO;
    if (indexPath.section == 1) {
        [_commentView.inputView becomeFirstResponder];//回复某人
        _commentView.inputView.placeholder = @"回复哪吒..";
        //评论点击事件
        __weak typeof(self)weakSelf = self;
        [_commentView.publishBtn addHander:^{
            [weakSelf commentAndReplyWithType:1];//回复
        }];
        
    }
}

#pragma mark - *******feedDelegate*******
///关注按钮被点击
- (void)followBtnClicked:(FeedCell *)feedCell button:(UIButton *)followBtn{
    if([followBtn.titleLabel.text isEqualToString:@"关注"]){
        [followBtn setTitle:@"取消关注" forState:UIControlStateNormal];
    }else{
        [followBtn setTitle:@"关注" forState:UIControlStateNormal];
    }
}

///价值按钮被点击
- (void)moneyBtnClicked:(FeedCell *)feedCell view:(UIView *)view{
    [SVProgressHUD showInfoWithStatus:@"预计一周后的收入"];
    [SVProgressHUD dismissWithDelay:0.5];
}

///点赞按钮被点击
- (void)thumbBtnClicked:(FeedCell *)feedCell view:(UIView *)view{
    for (UIView *subview in view.subviews) {
        if ([subview isKindOfClass:[UIImageView class]]) {
            UIImageView *imageView = (UIImageView *)subview;
            if ([imageView.image isEqual:[UIImage imageNamed:@"good"]]) {
                imageView.image = [UIImage imageNamed:@"good-filling"];
            }else if ([imageView.image isEqual:[UIImage imageNamed:@"good-filling"]]) {
                [SVProgressHUD showErrorWithStatus:@"请勿重复点赞"];
                [SVProgressHUD dismissWithDelay:0.5];
                break;
            }
        }
        if ([subview isKindOfClass:[UILabel class]]) {
            UILabel *label = (UILabel *)subview;
            [label setText:[NSString stringWithFormat:@"%ld",(label.text.integerValue + 1)]];
        }
        
    }
}

///评论按钮被点击
- (void)commentBtnClicked:(FeedCell *)feedCell view:(UIView *)view{
    
}

///收藏按钮被点击
- (void)collectionBtnClicked:(FeedCell *)feedCell button:(UIButton *)collcetionBtn{
    collcetionBtn.selected = collcetionBtn.selected ? NO : YES;
    [collcetionBtn setImage:[UIImage imageNamed:@"favorites-filling.png"] forState:UIControlStateSelected];
    if (collcetionBtn.selected) {
        [SVProgressHUD showSuccessWithStatus:@"成功收藏"];
    }else{
        [SVProgressHUD showSuccessWithStatus:@"取消收藏"];
    }
    [SVProgressHUD dismissWithDelay:0.5];
}

///头像被点击
- (void)avatorClicked:(NSString *)accountID{
    VisitViewController *visit = [[VisitViewController alloc]init];
    [self.navigationController pushViewController:visit animated:YES];
}

///预览图片
- (void)photosClicked:(NSArray *)photos{
    NSMutableArray <UIImage *>* images = [[NSMutableArray alloc]init];
    for (NSString *name in photos){
        UIImage *image = [UIImage imageNamed:name];
        [images addObject:image];
    }
    XLPhotoBrowser *browser = [XLPhotoBrowser showPhotoBrowserWithImages:images currentImageIndex:0];
    [browser setActionSheetWithTitle:nil delegate:self cancelButtonTitle:@"取消" deleteButtonTitle:nil otherButtonTitles:@"保存图片",nil];
    
}

#pragma mark - *******XLPhotoBrowserDelegate*******
- (void)photoBrowser:(XLPhotoBrowser *)browser clickActionSheetIndex:(NSInteger)actionSheetindex currentImageIndex:(NSInteger)currentImageIndex{
    
    switch (actionSheetindex) {
        case 0: {[browser saveCurrentShowImage];}// 保存
            break;
        default:
            break;
    }
}

#pragma mark - *******添加测试数据*******
- (NSMutableArray *)addTestData{
    NSMutableArray *Data = [[NSMutableArray alloc]init];
    for (int i = 1; i < 2; i++) {
        NSDictionary* dic = @{@"imageName":@"avator1.png",
                              @"name":@"胖虎",
                              @"devote":@"30",
                              @"photos":@[@"风景13",@"风景14",@"风景15",@"风景16"],
                              @"postContent":@"西湖的音乐喷泉很不错哦！",
                              @"location":@"杭州市",
                              @"time":@"1小时前",
                              @"moneyNum":@"23",
                              @"thumbNum":@"97",
                              @"commentNum":@"4",
                              @"tags":@"风景",
                        };
        FeedModel *model = [[FeedModel alloc]initWithFeedModel:dic];
        [Data addObject:model];
    }
    return Data;
}

- (NSMutableArray *)addCommentData{
    NSMutableArray *Data = [[NSMutableArray alloc]init];
    NSArray *avatorArr = @[@"avator2.png",@"avator3.png",@"avator4.png",@"avator5.png"];
    NSArray *nameArr = @[@"叮当猫",@"哪吒",@"球球",@"可达鸭"];
    NSArray *timeArr = @[@"刚刚",@"2小时前",@"7小时前",@"1天前"];
    NSArray *commentArr = @[@"喜欢",@"赞！",@"有点意思",@"真的好可爱"];
    for (int i = 1; i < 5; i++) {
        NSDictionary *dic = @{@"avator":avatorArr[i - 1],
                              @"name":nameArr[i - 1],
                              @"time":timeArr[i - 1],
                              @"comment":commentArr[i - 1],
                              };
        CommentModel *model = [[CommentModel alloc]initWithCommentModel:dic];
        [Data addObject:model];
    }
    return Data;
}

#pragma mark - *******键盘弹出会调用*******
- (void)keyboardWillChangeFrame:(NSNotification *)note
{
    // 获取键盘frame
    CGRect endFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    // 获取键盘弹出时长
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
  
    // 约束动画
    [UIView animateWithDuration:duration animations:^{
        //评论视图上下平移
        _commentView.transform = CGAffineTransformMakeTranslation(0, endFrame.origin.y - self.view.llz_height);
    }];
    
    if (endFrame.origin.y >= SCREEN_HEIGHT && _commentView.inputView.text.length <= 1){//取消回复
        _commentView.inputView.placeholder = @"评论点什么";
    }
}

#pragma mark - *******私有方法*******
- (void)commentAndReplyWithType:(NSInteger)type{
    __weak typeof(self)weakSelf = self;
    NSString *comment = weakSelf.commentView.inputView.text;
    NSString *name = @"Kylin";
    if (type == 1) {//reply
        name = @"Kylin 回复 哪吒";
        [SVProgressHUD showSuccessWithStatus:@"回复成功"];
    }else{
        [SVProgressHUD showSuccessWithStatus:@"评论成功"];
    }
    NSDictionary *dic = @{@"name":name,@"avator":@"avator3.png",@"time":@"刚刚",@"comment":comment};
    CommentModel *model = [[CommentModel alloc]initWithCommentModel:dic];
    [weakSelf.commentData insertObject:model atIndex:0];
    [weakSelf.tableview reloadData];
    //收回键盘提示发表成功
    [weakSelf.commentView.inputView resignFirstResponder];
    weakSelf.commentView.inputView.text = nil;
    [SVProgressHUD dismissWithDelay:1.0];
}

@end
